/* Copyright (c) 2006, 2009, Carl Burch. License information is located in the
 * com.cburch.logisim.Main source code and at www.cburch.com/logisim/. */
 
package com.cburch.draw.canvas;

import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JComponent;

/**
 * This is a lightweight class responsible for coordinating the 
 * painting of Tools and CanvasModels.
 *
 */
public class Canvas extends JComponent {
    public static final String TOOL_PROPERTY = "tool";
    public static final String MODEL_PROPERTY = "model";
    
    private CanvasModel model;
    private CanvasListener listener;
    private Selection selection;
    
    /**
     * Creates a new Canvas.
     */
    public Canvas() {
        model = null;
        listener = new CanvasListener(this);
        selection = new Selection();
        
        addMouseListener(listener);
        addMouseMotionListener(listener);
        addKeyListener(listener);
        setPreferredSize(new Dimension(200, 200));
    }

    /**
     * Returns the current <code>CanvasModel</code>
     * @return
     */
    public CanvasModel getModel() {
        return model;
    }
    
    /**
     * Returns the current <code>CanvasTool</code>.
     * @return
     */
    public CanvasTool getTool() {
        return listener.getTool();
    }
    
    /**
     * Returns the current selection.
     * @return
     */
    public Selection getSelection() {
        return selection;
    }
    
    /**
     * Sets the current model to the specified <code>CanvasModel</code>
     * @param value
     */
    public void setModel(CanvasModel value) {
        CanvasModel oldValue = model;
        if(oldValue != value) {
            if(oldValue != null) oldValue.removeCanvasModelListener(listener);
            model = value;
            if(value != null) value.addCanvasModelListener(listener);
            selection.clearSelected();
            repaint();
            firePropertyChange(TOOL_PROPERTY, oldValue, value);
        }
    }
    
    /**
     * Sets the active tool to the specified <code>CanvasTool</code>
     * @param value
     */
    public void setTool(CanvasTool value) {
        CanvasTool oldValue = listener.getTool();
        if(value != oldValue) {
            listener.setTool(value);
            firePropertyChange(TOOL_PROPERTY, oldValue, value);
        }
    }
    
    /**
     * Redraws the Canvas, along with the circuit and tools.
     */
    public void paintComponent(Graphics g) {
        CanvasModel model = this.model;
        CanvasTool tool = listener.getTool();
        g.clearRect(0, 0, getWidth(), getHeight());
        if(model != null) {
            Graphics dup = g.create();
            model.paint(g, selection);
            dup.dispose();
        }
        if(tool != null) {
            Graphics dup = g.create();
            tool.draw(this, dup);
            dup.dispose();
        }
    }
}
